package com.fqcar.fqdf.core.http;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.fqcar.fqdf.DFApp;
import com.fqcar.fqdf.entity.ResponseEntity;
import com.fqcar.fqdf.util.SharedPreferenceUtil;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.fqdf.framework.android.util.EnvUtil;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResponseEntityRequest extends Request<ResponseEntity> {

    private Map<String, String> params = null;
    private static RetryPolicy mRetryPolicy = null;
    private static HashMap<String, String> headers = null;
    private Listener<ResponseEntity> mListener;
    //	private ErrorListener errorListener;
    private GofunErrorListener gofunErrorListener;
    private Context context;

    private static List<String> noToastRequestUrl = new ArrayList<>();

    static {
        mRetryPolicy = new DefaultRetryPolicy(3 * 60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        headers = new HashMap<String, String>();
    }

    public ResponseEntityRequest(String url, Context act) {
        this(url, null, act);
    }

    public ResponseEntityRequest(String url, Listener<ResponseEntity> listener, Context act) {
        this(url, null, listener, act);
    }

    public ResponseEntityRequest(String url, Map<String, String> params, Listener<ResponseEntity> listener, Context act) {
        this(url, params, listener, null, act);
    }

    public ResponseEntityRequest(String url, Map<String, String> params, Listener<ResponseEntity> listener, GofunErrorListener gofunErrorListener, Context act) {
        super(Method.POST, url, null);
        this.params = params == null ? new HashMap<String, String>() : params;
        this.removeEmptyParamKeyAndValue();
        this.mListener = listener;
        this.context = act;
//		this.errorListener = errorListener;
        this.gofunErrorListener = gofunErrorListener;
        setShouldCache(false);
        setTag(act.getClass().getName());
        setRetryPolicy(mRetryPolicy);
        //添加token
        headers.put("Authorization", SharedPreferenceUtil.getStringSPAttrs(context, SharedPreferenceUtil.AttrInfo.USER_TOKEN, ""));
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
//		return super.getHeaders();
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
//		LogUtil.i(getClass(), this.params.toString());
        return this.params;
    }

    @Override
    protected Response<ResponseEntity> parseNetworkResponse(NetworkResponse response) {
        try {

            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            ResponseEntity request = JSON.parseObject(jsonString, ResponseEntity.class);
            return Response.success(request, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(ResponseEntity response) {
        try {
            if (response.code == ResponseEntity.SERVER_NO_EXCEPTION_CODE
                    /*|| ResponseEntity.USER_VALIDATE_UNFINISH == response.code
					|| ResponseEntity.USER_VALIDATE_WAIT == response.code
					|| ResponseEntity.USER_VALIDATE_NO_PASS == response.code
					|| ResponseEntity.USER_CREDIT_UNBIND == response.code
					|| ResponseEntity.ORDER_STATUS_ERROR == response.code
					|| ResponseEntity.ORDER_PAY_RESULT == response.code
					|| ResponseEntity.ORDER_STATUS_UNPAY == response.code
					|| ResponseEntity.ORDER_CAN_NOT_RETURN == response.code*/) {
                mListener.onResponse(response);
            } else if (null != this.gofunErrorListener) {
                this.gofunErrorListener.onFailure(new ResponseError(response.code, response.desc, true, response.modelData));
				/*if(null != mListener){
					mListener.onResponse(response);
				} else {
					if(null != context && !checkUrlIfShowError()){
						Toast.makeText(context, response.desc, Toast.LENGTH_SHORT).show();
					}
				}*/
            }

			/*if(ResponseEntity.SERVER_NO_EXCEPTION_CODE == response.code
					|| ResponseEntity.USER_VALIDATE_UNFINISH == response.code
					|| ResponseEntity.USER_VALIDATE_WAIT == response.code
					|| ResponseEntity.USER_VALIDATE_NO_PASS == response.code
					|| ResponseEntity.USER_CREDIT_UNBIND == response.code
					|| ResponseEntity.ORDER_STATUS_ERROR == response.code){
				if(null != mListener){
					mListener.onResponse(response);
				} else {
					if(null != context && !checkUrlIfShowError()){
						Toast.makeText(context, response.desc, Toast.LENGTH_SHORT).show();
					}
				}
			}else if(ResponseEntity.TOKEN_FAIL == response.code){
				if(null != context){
					SharedPreferenceUtil.clearSP(context.getApplicationContext(), SharedPreferenceUtil.SP_NAME_USER);
					Intent intent = new Intent(context, LoginActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("content", "您的登陆信息已经失效，请重新登陆");
					context.startActivity(intent);
				}
			}else{
				Toast.makeText(context, response.desc, Toast.LENGTH_SHORT).show();
			}*/
        } catch (Exception e) {
			/*if(null != context || !checkUrlIfShowError()){
				StringBuffer sb = new StringBuffer();
				for(StackTraceElement trace : e.getStackTrace()){
					sb.append(trace.getClassName()).append(".").append(trace.getMethodName())
					.append("(").append(trace.getFileName()).append(":")
					.append(trace.getLineNumber()).append(")").append("\r\n");
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setMessage(sb.toString());
				builder.create().show();
			}*/
            e.printStackTrace();
        }
    }

    @Override
    public void deliverError(VolleyError error) {
        if (this.gofunErrorListener != null) {
            this.gofunErrorListener.onFailure(new ResponseError(-1000, error.getLocalizedMessage(), false, null));
        }
		/*if(context != null){
			MobclickAgent.reportError(context, error.getCause());
		}
		if(null != context && !checkUrlIfShowError()){
//			Toast.makeText(context, context.getString(R.string.network_error), Toast.LENGTH_SHORT).show();
		}
		if(null != errorListener){
			errorListener.onErrorResponse(error);
		}*/
    }

    @Override
    public String getUrl() {
        StringBuffer sb = new StringBuffer(super.getUrl());
        sb.append("?").append("os=").append("android");//系统
        sb.append("&").append("deviceId=").append(EnvUtil.getDeviceId(context));//deviceId
        sb.append("&").append("deviceType=").append(EnvUtil.getPhoneType(context));//手机型号
        sb.append("&").append("marketId=").append(EnvUtil.getChannelName(context));//渠道号
        sb.append("&").append("versionId=").append(EnvUtil.getPhoneSysVersion(context));//手机系统版本
        sb.append("&").append("appVersion=").append(EnvUtil.getAppVersionCode(context)); //versionCode
//		sb.append("&").append("cityCode=").append(Constants.cityCode);

        String cityCode = ((DFApp) context.getApplicationContext()).getCityCode();
        if (!CheckLogicUtil.isEmpty(cityCode)) {
            sb.append("&").append("cityCode=").append(cityCode);
        }
        sb.append("&").append("sourceFor=").append(EnvUtil.getSOURCE_FOR(context));
//		sb.append("&").append("versionName=").append(EnvUtil.getAppVersionName(context));//versionName
        return sb.toString();
    }

    /**
     * 检查错误时是否弹出提示
     *
     * @return
     */
    private boolean checkUrlIfShowError() {
        return noToastRequestUrl.contains(getUrl().split("\\?")[0]);
    }


    /**
     * 检查参数是否包含null的key或者value
     *
     * @return
     */
    private void removeEmptyParamKeyAndValue() {
        List<String> prepareToRemoveKeys = new ArrayList<String>();
        for (String key : this.params.keySet()) {
            String value = this.params.get(key);
            if (key == null || value == null) {
                prepareToRemoveKeys.add(key);
            }
        }
        if (!prepareToRemoveKeys.isEmpty()) {
            for (String prepareToRemoveKey : prepareToRemoveKeys) {
                this.params.remove(prepareToRemoveKey);
            }
        }
    }
}